<template>
  <div class="resident-manage">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>住户管理</h2>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>区域管理</el-breadcrumb-item>
          <el-breadcrumb-item>住户管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增住户
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline :label-width="80">
        <el-form-item label="所属社区">
          <el-select
            v-model="searchForm.communityId"
            placeholder="请选择社区"
            clearable
            style="width: 200px"
            @change="handleCommunityChange"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.id"
              :label="item.communityName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属楼栋">
          <el-select
            v-model="searchForm.buildingId"
            placeholder="请选择楼栋"
            clearable
            style="width: 200px"
            @change="handleBuildingChange"
          >
            <el-option
              v-for="item in buildingOptions"
              :key="item.id"
              :label="item.buildingName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属单元">
          <el-select
            v-model="searchForm.unitId"
            placeholder="请选择单元"
            clearable
            style="width: 150px"
            @change="handleUnitChange"
          >
            <el-option
              v-for="item in unitOptions"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属房户">
          <el-select
            v-model="searchForm.householdId"
            placeholder="请选择房户"
            clearable
            style="width: 200px"
            @change="handleHouseholdChange"
          >
            <el-option
              v-for="item in householdOptions"
              :key="item.id"
              :label="`${item.roomNumber}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input 
            v-model="searchForm.realName" 
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="身份">
          <el-select 
            v-model="searchForm.residentType" 
            placeholder="请选择身份"
            clearable
            style="width: 150px"
          >
            <el-option label="户主" :value="1" />
            <el-option label="家庭成员" :value="2" />
            <el-option label="租客" :value="3" />
            <el-option label="临时居住" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="正常居住" :value="1" />
            <el-option label="已搬出" :value="0" />
            <el-option label="暂时外出" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 住户列表 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>住户列表</span>
          <div class="header-actions">
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="residentList" 
        border 
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="realName" label="姓名" min-width="100" />
        <el-table-column prop="phone" label="联系电话" min-width="120" />
        <el-table-column prop="communityName" label="所属社区" min-width="120" />
        <el-table-column prop="buildingName" label="所属楼栋" min-width="100" />
        <el-table-column prop="unitName" label="所属单元" min-width="100" />
        <el-table-column prop="roomNumber" label="房户号" min-width="100" />
        <el-table-column prop="residentTypeName" label="身份" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getResidentTypeTagType(row.residentType)">
              {{ row.residentTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="moveInDate" label="入住日期" min-width="120" />
        <el-table-column prop="statusName" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getResidentStatusTagType(row.status)">
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="residentList.length > 0">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && residentList.length === 0">
      <el-empty
        :description="emptyStateMessage"
        :image-size="200"
      >
        <template #description>
          <div class="empty-description">
            <p>{{ emptyStateMessage }}</p>
            <p class="empty-sub-description">{{ emptyStateDescription }}</p>
          </div>
        </template>
        <template #extra>
          <div class="empty-actions">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增住户
            </el-button>
          </div>
        </template>
      </el-empty>
    </div>

    <!-- 新增/编辑弹窗 - 已移除，改为独立页面 -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Download, Edit, Delete } from '@element-plus/icons-vue'
import { useResidentStore } from '@/store/resident'
import { useHouseholdStore } from '@/store/household'
import { useUserStore } from '@/store/user'
import { ROLE_CODES } from '@/constants/roles'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { householdApi } from '@/api/household'
import { showMessage } from '@/utils/message'
import { residentApi } from '@/api/resident'

// 定义接口
interface SearchForm {
  communityId?: number | undefined
  buildingId?: number | undefined
  unitId?: number | undefined
  householdId?: number | undefined
  realName?: string
  residentType?: number | undefined
  status?: number | undefined
}

interface Pagination {
  current: number
  size: number
  total: number
}

interface FormData {
  id?: number | undefined
  residentId?: number | undefined
  residentType?: number | undefined
  moveInDate?: string | undefined
  contractStartDate?: string | undefined
  contractEndDate?: string | undefined
  monthlyRent?: number | undefined
  deposit?: number | undefined
  contractNo?: string | undefined
  remark?: string | undefined
}

// 响应式数据
const loading = ref(false)
const selectedRows = ref<any[]>([])
// 移除currentHouseholdName，因为不再需要从URL参数获取房户信息

const searchForm = reactive<SearchForm>({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  householdId: undefined as number | undefined,
  realName: '',
  residentType: undefined as number | undefined,
  status: undefined as number | undefined
})

const pagination = reactive<Pagination>({
  current: 1,
  size: 10,
  total: 0
})

// 移除formData，因为不再需要弹窗表单

// Router
const router = useRouter()

// Store
const residentStore = useResidentStore()
const householdStore = useHouseholdStore()
const userStore = useUserStore()

// 权限检查
const isSuperAdmin = computed(() => userStore.hasRole(ROLE_CODES.SUPER_ADMIN))
const hasPropertyCompany = computed(() => userStore.checkUserHasPropertyCompany())

// 计算属性
const residentList = computed(() => residentStore.residentList)
const householdOptions = ref<any[]>([])

// 联动选项数据
const communityOptions = ref<any[]>([])
const buildingOptions = ref<any[]>([])
const unitOptions = ref<any[]>([])

// 空状态处理
const emptyStateMessage = computed(() => {
  if (loading.value) {
    return '正在加载数据...'
  }
  if (searchForm.householdId) {
    return '暂无住户数据'
  }
  return '请选择房户查看住户信息'
})

const emptyStateDescription = computed(() => {
  if (searchForm.householdId) {
    return '您可以点击下方按钮新增住户'
  }
  return '您可以点击下方按钮新增住户'
})

// 方法
const loadResidentList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    // 过滤undefined值和空字符串
    Object.keys(params).forEach(key => {
      if ((params as any)[key] === undefined || (params as any)[key] === '') {
        delete (params as any)[key]
      }
    })
    
    // 后端会自动根据用户权限过滤数据，前端直接传递查询条件即可
    await residentStore.getResidentList(params)
    pagination.total = residentStore.total
  } catch (error) {
    console.error('加载住户列表失败:', error)
    ElMessage.error({ message: '加载住户列表失败', type: 'error' })
    // 出错时清空列表
    residentStore.residentList = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const loadCommunityOptions = async () => {
  try {
    // 后端会自动根据用户权限过滤社区列表，前端直接调用即可
    const response = await communityApi.getCommunityList({})
    communityOptions.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('加载社区数据失败:', error)
    showMessage({ type: 'error', message: '加载社区数据失败' })
    communityOptions.value = []
  }
}

const loadHouseholdList = async () => {
  // 这个方法现在由联动逻辑处理，不再需要单独加载
}

const handleSearch = () => {
  pagination.current = 1
  loadResidentList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    communityId: undefined,
    buildingId: undefined,
    unitId: undefined,
    householdId: undefined,
    realName: '',
    residentType: undefined,
    status: undefined
  })
  buildingOptions.value = []
  unitOptions.value = []
  householdOptions.value = []
  pagination.current = 1
  loadResidentList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadResidentList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadResidentList()
}

// 社区变化处理
const handleCommunityChange = async (communityId: number | undefined) => {
  searchForm.buildingId = undefined
  searchForm.unitId = undefined
  searchForm.householdId = undefined
  buildingOptions.value = []
  unitOptions.value = []
  householdOptions.value = []
  
  if (communityId) {
    try {
      const response = await buildingApi.getBuildingsByCommunity(communityId)
      buildingOptions.value = Array.isArray(response.data) ? response.data : []
    } catch (error) {
      console.error('加载楼栋数据失败:', error)
      showMessage({ type: 'error', message: '加载楼栋数据失败' })
      buildingOptions.value = []
    }
  }
  
  // 重新加载住户列表
  loadResidentList()
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number | undefined) => {
  searchForm.unitId = undefined
  searchForm.householdId = undefined
  unitOptions.value = []
  householdOptions.value = []
  
  if (buildingId) {
    try {
      const response = await unitApi.getUnitsByBuilding(buildingId)
      unitOptions.value = Array.isArray(response.data) ? response.data : []
    } catch (error) {
      console.error('加载单元数据失败:', error)
      showMessage({ type: 'error', message: '加载单元数据失败' })
      unitOptions.value = []
    }
  }
  
  // 重新加载住户列表
  loadResidentList()
}

// 单元变化处理
const handleUnitChange = async (unitId: number | undefined) => {
  searchForm.householdId = undefined
  householdOptions.value = []
  
  if (unitId) {
    try {
      const response = await householdApi.getHouseholdsByUnit(unitId)
      householdOptions.value = Array.isArray(response.data) ? response.data : []
    } catch (error) {
      console.error('加载房户数据失败:', error)
      showMessage({ type: 'error', message: '加载房户数据失败' })
      householdOptions.value = []
    }
  }
  
  // 重新加载住户列表
  loadResidentList()
}

// 房户变化处理
const handleHouseholdChange = (householdId: number | undefined) => {
  // 重新加载住户列表
  loadResidentList()
}

// 新增住户
const handleAdd = () => {
  router.push('/region/resident/add')
}

// 编辑住户
const handleEdit = (row: any) => {
  router.push(`/region/resident/edit/${row.id}`)
}

// 删除住户
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要移除该住户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await residentStore.deleteResident(row.id)
    ElMessage.error({ message: '移除成功', type: 'success' })
    loadResidentList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除住户失败:', error)
      ElMessage.error({ message: '移除住户失败', type: 'error' })
    }
  }
}

// 导出
const handleExport = () => {
  ElMessage.error({ message: '导出功能开发中...', type: 'info' })
}

// 移除handleFormSuccess，因为不再需要弹窗表单

// 选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

const getResidentTypeTagType = (type: number) => {
  switch (type) {
    case 1: return 'success' // 户主
    case 2: return 'info'    // 家庭成员
    case 3: return 'warning' // 租客
    case 4: return 'danger'  // 临时居住
    default: return ''
  }
}

const getResidentStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success' // 正常居住
    case 0: return 'danger'  // 已搬出
    case 2: return 'warning' // 暂时外出
    default: return ''
  }
}

// 住户相关API调用已在 residentApi 统一处理为 /api/region/resident 路径，无需页面内再拼接路径。

// 生命周期
onMounted(() => {
  console.log('住户管理页面初始化开始')
  console.log('权限检查:', {
    isSuperAdmin: isSuperAdmin.value,
    hasPropertyCompany: hasPropertyCompany.value,
    userRoles: userStore.userRoles,
    hasCompany: userStore.hasCompany
  })
  // 初始化数据
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    // 加载社区选项（后端会自动根据用户权限过滤）
    await loadCommunityOptions()
    
    // 如果有社区数据，自动选择第一个社区并触发联动
    if (communityOptions.value.length > 0) {
      const firstCommunityId = communityOptions.value[0].id
      if (firstCommunityId) {
        searchForm.communityId = firstCommunityId
        await handleCommunityChange(firstCommunityId)
      }
    } else {
      // 如果没有社区数据，直接加载住户列表（后端会根据权限过滤）
      await loadResidentList()
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error({ message: '初始化数据失败', type: 'error' })
  }
}
</script>

<style scoped>
.resident-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  
  .empty-description {
    text-align: center;
    
    p {
      margin: 8px 0;
      color: #909399;
    }
    
    .empty-sub-description {
      font-size: 14px;
      color: #c0c4cc;
    }
  }
  
  .empty-actions {
    margin-top: 20px;
  }
}
</style> 